import { _decorator, Component, EventTouch, Mat4, Node, tween, Vec2, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('onTouch')
export class onTouch extends Component {
    @property(Node)
    Rope: Node = null;

    private kaiguan: Boolean = false;
    myTween;

    touchx;
    touchy;

    //被托拽的马
    @property(Node)
    catchHorse:Node = null;

    start() {
        globalThis.onTouch = this;
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    }



    onTouchStart(_e: EventTouch) {

        if(this.kaiguan){
            return;
        }
        this.catchHorse.active = false;
        this.Rope.active = true;
        // 获取触摸点的位置（世界坐标）
        const touchPos = _e.getUILocation();
        this.touchx = touchPos.x;
        this.touchy = touchPos.y;
        
        let thisnode = this.node;
        // 世界坐标 worldPosition
        let worldPosition = new Vec3(touchPos.x, -308.122, 0);

        let worldMatrix = thisnode.getWorldMatrix(new Mat4());
        let invertedMatrix = Mat4.invert(new Mat4(), worldMatrix);
        let localPosition = new Vec3();
        Vec3.transformMat4(localPosition, worldPosition, invertedMatrix);
        this.Rope.setPosition(localPosition);
        
        
        let touchposy = touchPos.y;
        let moveUp = touchposy + 50;
        
        this.kaiguan = true;
        this.myTween = tween(this.Rope)
        .by(1, { position: new Vec3(0, moveUp, 0) })
        .by(1, { position: new Vec3(0, -moveUp, 0) })
        .call(() => {
            this.Rope.setPosition(localPosition);
            this.kaiguan = false;
            
        }).start();
    }

    touchHorse(y){
        
        let touchx = this.touchx;
        let touchy = this.touchy;
        let touchyy = touchy+250;
        
        this.Rope.active = false;
        this.catchHorse.active = true;

        // 设置为马当前的位置
        this.catchHorse.setPosition(new Vec3(touchx-301.065,y-600,0));
        this.myTween = tween(this.catchHorse)
        .by(1, { position: new Vec3(0, -touchyy, 0) })
        .call(() => {
            
        }).start();
    }

}

